package com.zl.customer.web;

import com.zl.customer.pojo.Userinfo;
import com.zl.customer.service.UserinfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

@Controller
@RequestMapping("/user")
public class UserinfoController {
    @Autowired
    private UserinfoService userinfoService;

    @PostMapping("/login")
    public String login(@RequestParam(name="username",required = true) String name, String password, String remenber, HttpServletRequest request, HttpServletResponse response){
        Userinfo userinfo = userinfoService.login(name, password);
        if(userinfo == null){  //登录失败
            // "用户名或密码错误"
            // 域对象
            request.setAttribute("errorMsg","用户名或密码错误");//安全性
            //5.页面跳转
            return "forward:/login.jsp";
        }else{  //登录成功
            if("rmb".equals(remenber)){ //勾选  //避免出现空指针异常
                //创建cookie
                Cookie nameCookie = new  Cookie("name",name);
                Cookie  passCookie = new  Cookie("pass",password);

                //Cookie的默认存活时间: -1   7天有效
                nameCookie.setMaxAge(7*24*60*60);
                passCookie.setMaxAge(7*24*60*60);

                //保存到客户端
                response.addCookie(nameCookie);
                response.addCookie(passCookie);
            }else{//没有勾选 不记住密码,  清除cookie
                Cookie[] cookies =  request.getCookies();
                if(cookies!=null && cookies.length > 0){
                    for(Cookie cookie : cookies){
                        if(cookie.getName().equals("name") || cookie.getName().equals("pass")){
                            //删除cookie
                            cookie.setMaxAge(0);

                            //保存给客户端
                            response.addCookie(cookie);
                        }
                    }
                }
            }

            //把用户信息保存到Session域中
            //1.得到Session对象
            HttpSession session = request.getSession();
            //2.把用户信息保存到session域
            session.setAttribute("loginUser",userinfo);
            Object jumpUrl = session.getAttribute("jumpUrl");

            return "redirect:/index.do";

        }
    }
}
